package lzw;

import java.io.IOException;
import java.io.OutputStream;

public class Output  extends InputOutput {        
        private OutputStream out;
        /**
         * Number of codes currently written to the backing stream.
         */
        private int written;

        public Output(OutputStream out, int codeWordLength) {
                this.out = out;
                this.codeWordLength = codeWordLength;
                written = 0;
                buffer = 0;
                bufferUsageBits = (int) Euclid.leastCommonMultiple(BYTE_SIZE, codeWordLength);
                bufferUsageBytes = bufferUsageBits / BYTE_SIZE;
                bufferUsageSymbols = bufferUsageBits / codeWordLength;
                mask = (1 << codeWordLength) - 1;
        }


        public void write(int code) throws IOException {
            code = (code & mask) << ((written) * codeWordLength);
            buffer |= code;
            written++;
            if (written >= bufferUsageSymbols) {
                for (int i = 0; i < bufferUsageBytes; i++) {
                    out.write((int) (buffer & BYTE_MASK));
                    buffer >>= BYTE_SIZE;
                }
                written = 0;
                buffer = 0;
            }
        }
        
        public void flush() throws IOException {
            while ((written < bufferUsageSymbols) && (written != 0)) {
                write(-1);
            }
            out.flush();
        }
        
        public void close() throws IOException {
            out.close();
        }
}